package com.ly.jvm;


import java.util.concurrent.atomic.AtomicReference;

class SpinLock {
    private AtomicReference<Integer> atomicReference = new AtomicReference<>(null);

    public void myLock() {
        System.out.println(Thread.currentThread().getName() +" come in");
        while(!atomicReference.compareAndSet(null,1)) {

        }
    }

    public void myUnlock() {
        atomicReference.compareAndSet(1, null);
        System.out.println(Thread.currentThread().getName() +" unlock ");
    }
}

public class SpinLockDemo {

    public static void main(String[] args) throws InterruptedException {
        SpinLock spinLock = new SpinLock();

        new Thread(()-> {
            spinLock.myLock();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            spinLock.myUnlock();
        },"A").start();

        Thread.sleep(1000);
        new Thread(()-> {
            spinLock.myLock();
            spinLock.myUnlock();
        },"B").start();
    }

}
